var util = require('../../util/util.js')
var formatLocation = util.formatLocation

let app = getApp();
let jumpurl=app.jumpurl.url;
var bmap = require('../../libs/bmap-wx.js');
var wxMarkerData = []; 
var lishi=[];
var address;
var addresslist = [];
var id_now;
let c_location;
var c_latitude;
var c_longitude;
var historyList = [];

Page({
  data: {
    winHeight: "",//窗口高度
    currentTab1: 0, //预设当前项的值
    scrollLeft: 0, //tab标题的滚动条位置
    expertList: [{ //假数据
      img: "avatar.png",
      name: "欢顔",
      tag: "知名情感博主",
      answer: 134,
      listen: 2234,
      inputTxt: ''
    }],
    addresslist: [{
      title: 111,
      addr: "jiangsuzhousheng"
    }, {
      title: "徐州万创网络科技有限公司",
      addr: "江苏省徐州市鼓楼区创意文化科技产业园A2-1楼"
    },

    ],
    addrlist: [{
      id: 1,
      name: "zhangsan",
      tel: "13625632541",
      address: "江苏省徐州市鼓楼区创意文化科技产业园A2-1楼江苏省徐州市鼓楼区创意文化科技产业园A2-1楼"
    }
    ],
   

    history_flag: true,
    addr_grey_flag: false,
    hasaddr: false,
    gobackflag: false
    
    
    // 百度地图
    // markers: [],
    // latitude: '',
    // longitude: '',
    // placeData: {} 

  },
  
  // 滚动切换标签样式
  switchTab: function (e) {
    this.setData({
      currentTab1: e.detail.current
    });
    this.checkCor();
  },
  // 点击标题切换当前页时改变样式
  swichNav: function (e) {
    var cur = e.target.dataset.current;
    if (this.data.currentTaB1 == cur) { return false; }
    else {
      this.setData({
        currentTab1: cur
      })
    }
  },
  //判断当前滚动超过一屏时，设置tab标题滚动条。
  checkCor: function () {
    if (this.data.currentTab > 4) {
      this.setData({
        scrollLeft: 300
      })
    } else {
      this.setData({
        scrollLeft: 0
      })
    }
  },
  onLoad: function (options) {
     var that = this;
     var jumpurl=app.jumpurl.url;
    that.setData({
      currentTab: options.id,
      lishi: []
    })
    //  wx.clearStorage();
    wx.getStorage({
      key: 'lishiSt',
      success: function (res) {

        that.setData({
          lishi: lishi,
        })
        
        if (lishi.length < 1) {
          console.log("*****************0************")
          that.setData({
            history_flag: false,
          })
        } else {
          console.log("*****************else************")
          that.setData({
            history_flag: true
          })
        }

       
      }, error: function (err) {
        console.log("*************err***************");
        console.log(err);
      }

    })

    //请求数据
    wx.request({
      url: jumpurl + 'address/name',
      data: {
        currentTab: options.id,
        openid: app.userList.openid
      },
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded" //post
      },
      success: function (res) {
        console.log(res);
        if(res.data.shouddress.length>0){
          var fhr = res.data.shouddress[0].name;
          var tel = res.data.shouddress[0].tel;
          that.setData({
            setname: fhr,
            phone: tel
          })
        }
        
      },
      fail: function (err) {
        console.log(err);
      }
    })
  

    //  20180712modify
     ///获取定位信息
     wx.getLocation({
       type: 'wgs84',
       success: function (res) {
          that.setData({
            location: formatLocation(res.longitude, res.latitude),
            latitude:res.latitude,
            longitude:res.longitude,
            
            markers: [{
              id: 1,
              latitude: res.latitude,
              longitude: res.longitude,

            }],
            covers: [{
              latitude: res.latitude,
              longitude: res.longitude,
              iconPath: 'images/location.png'
            }, {
                latitude: res.latitude,
                longitude: res.longitude,
                iconPath: 'images/location.png'
            }]
         })


       }
     })

    var BMap = new bmap.BMapWX({
      ak: 'bzQsfmU86UsaqMOeZzXFrjbkVAUKcVYW'
    });
    // 发起POI检索请求 
    BMap.search({
      "query": '办公楼',
      fail: function (err) {
        console.log("err" + err);
      },
      success: function (res) {
        addresslist = res.wxMarkerData;
       
        that.setData({
          addresslist: addresslist
        })
      },

    }); 
   
    //  高度自适应
    wx.getSystemInfo({
      success: function (res) {
        var clientHeight = res.windowHeight,
          clientWidth = res.windowWidth,
          rpxR = 750 / clientWidth;
        var calc = clientHeight * rpxR - 180;
        // console.log(calc)
        that.setData({
          winHeight: calc
        });
      }
    });

    /***********判断地址选中********** */
    that.setData({
      chosedItem: 1

    })

  },
  
  /**********onshow**********/
  onShow: function () {
    var that = this;
   
    wx.getStorage({
      key: 'title',
      success: function (res) {
      
        that.setData({
          locationAddress: res.data
        })
      },
      fail: function (err) {
        console.log("调用缓存" + err)
      }
    })

    wx.getStorage({
      key: 'title_key',
      success: function (res) {
        console.log(res);
        that.setData({
          locationAddress: res.data,
          address2: ""
        })
      },
      fail: function (err) {
        console.log("调用缓存" + err)
      }
    })


    // wx.getStorage({
    //   key: 'map_add_key',
    //   success: function (res) {
      
    //     that.setData({
    //       locationAddress: res.data
    //     })
    //   },
    //   fail: function (err) {
    //     console.log("调用缓存" + err)
    //   }
    // })

    wx.getStorage({
      key: 'jingwei_key',
      success: function (res) {
      
        that.setData({
          jingwei: res.data
        })
      },
      fail: function (err) {
        console.log("调用缓存" + err)
      }
    })

    //调取历史地址
    wx.request({
      url: jumpurl + 'history/shou',
      data: {
        openid: app.userList.openid
      },
      success: function (res) {
      
        var lishi_address = res.data.shoulishi;
        console.log(lishi_address)
        if (lishi_address == 0) {
          that.setData({
            history_flag: false
          })
        } else {
          that.setData({
            history_flag: true,
            lishi: lishi_address
          })
        }
      },
      fail: function (err) {
        console.log("调用历史地址" + err)
      }
    })
  },


    /******监听返回事件************/
    goback:function() {
      var that = this;
      wx.showModal({
        title: '',
        content: '确定放弃本次编辑',
        showCancel: true,
        cancelText: "取消",
        cancelColor: "#666",
        confirmText: "确定",
        confirmColor: "#ffae58",
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击确定');
            wx.setStorage({
              key: 'map_add_key',
              data: '',
            })
            wx.setStorage({
              key: 'title_key',
              data: '',
            })
            wx.setStorage({
              key: 'jingwei_key',
              data: '',
            })
            wx.redirectTo({
              url: '/pages/index/index',
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }, fail: function () {
          console.log("fail");
        }

      })
      // that.setData({
      //   gobackflag:true
      // })
    },
    cancel: function() {
      var that = this;
      that.setData({
        gobackflag: false
      })
    },
    comfirm: function() {
      var that = this;
      that.setData({
        gobackflag: false
      })
      wx.redirectTo({
        url: '/pages/index/index',
      })
    },



  
 chooseLocation:function () {
   var that = this;
   wx.setStorage({
     key: 'lujing',
     data: 'get_info/get_info',
   })
   wx.navigateTo({
     url: '/pages/address/address',
   })

    // var that = this
    // wx.chooseLocation({
    //   success: function (res) {
    //     console.log(res)
    //     that.setData({
    //       c_location: formatLocation(res.longitude, res.latitude),
    //       locationAddress: res.address,
    //       c_latitude:res.latitude,
    //       c_longitude:res.longitude
    //     })
       
    //     var lishi_len = lishi.length;

    //     if (lishi_len == 0) {
    //       lishi.push(res);
    //     } else {
    //       var i;
    //       for (i = 0; i < lishi_len;) {

    //         if (res.address != lishi[i].address) {
    //           i++;
    //         } else {
    //           return;
    //         }
    //       }
    //       if (i == lishi_len) {
    //         lishi.push(res);
    //       }

    //     }
    //     console.log("****************lishidizhi*************")
    //     console.log("数组的长度" + lishi.length)
    //     console.log(lishi);
    //     wx.setStorage({
    //       key: 'lishiSt',
    //       data: lishi,
    //     })

    //   }
    // })
  },


  // showSearchInfo: function (data, i) {
  //   var that = this;
  //   that.setData({
  //     placeData: {
  //       title: '名称：' + data[i].title + '\n',
  //       address: '地址：' + data[i].address + '\n',
  //       // telephone: '电话：' + data[i].telephone
  //     }
  //   });
  // },


 
  //弹出常用地址列表
  pop_addr: function () {
    var that = this;
    console.log(app.userList.openid);
    //请求数据
    wx.request({
      url: jumpurl + 'often/index',
      data: {
        openid: app.userList.openid
      },
      success: function (res) {
        console.log(res);
        var changyong = res.data.changyong;
        if (changyong == 0) {
          that.setData({
            hasaddr: false
          })
        } else {

          that.setData({
            hasaddr: true,
            addrlist: res.data.changyong
          })

        }
      },
      fail: function (err) {
        console.log(err);
      }
    })


    var that = this;
    that.setData({
      addr_grey_flag: true
    })
  },

  //编辑
  edit: function () {
    wx.navigateTo({
      url: '/pages/addresslist/addresslist',
    })
    this.setData({
      addr_grey_flag: false
    })
  },

  //点击常用地址取消
  cancelBtn: function () {
    var that = this;
    that.setData({
      addr_grey_flag: false
    })
  },



  //点击常用地址列表  数据回填  隐藏经纬度一并回填
  choseItem: function (e) {
    var that = this;
    console.log(e);
    var id = e.currentTarget.dataset.id;
    var chosedItem = id;

    wx.request({
      url: jumpurl + 'huitian/index',
      data: {
        id: id,
        openid: app.userList.openid

      },
      success: function (res) {

        console.log(res)
        var address = res.data.msg.message.address;
        var jingwei = res.data.msg.message.jingwei;
        var map_add = res.data.msg.message.map_add;
        var name = res.data.msg.message.name;
        var tel = res.data.msg.message.tel;
        that.setData({

          addr_grey_flag: false,
          setname: name,
          phone: tel,
          locationAddress: map_add,
          address2: address,
          jingwei: jingwei
        })
      },
      fail: function (err) {
        console.log("回填地址" + err)
      }
    })
  },



  formBindsubmit: function (mobile) {
    console.log("..............mobile...........");
    console.log(mobile);
    var that= this;
    var jumpurl= app.jumpurl.url;
    var transmit = mobile.detail.value;
    var mobile = mobile.detail.value.phone; //传入首页的手机号
    var name = transmit.setname; //传入首页的用户名
    var address_1 = transmit.address1; //传入首页的地址1
    var address_2 = transmit.address2; //传入首页的详细地址
    var jingwei = transmit.jingwei;
    // id_now=transmit.id_now;
    if (mobile.length == 0) {
      wx.showToast({
        title: '请输入手机号！',
        icon: 'none',
        duration: 1500
      })
      return false;
    }
    if (mobile.length != 11) {
      wx.showToast({
        title: '手机号长度有误！',
        icon: 'none',
        duration: 1500
      })
      return false;
    }
    var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/;
    if (!myreg.test(mobile)) {
      wx.showToast({
        title: '手机号有误！',
        icon: 'none',
        duration: 1500
      })
      return false;
    }
    else{
    }
   
    
    if(!name){
      wx.showToast({
        title: '收货人姓名不能为空',
        icon:"none",
      })
      return false;
    }else if(!address_1){
      wx.showToast({
        title: '收货地址不能为空',
        icon:"none",
      })
      return false;
    }else{

    }

    wx.request({
      url: jumpurl + 'address/index',
      data: {
        openid: app.userList.openid,
        name: name,
        tel: mobile,
        map_add: address_1,
        address: address_2,
        jingwei: jingwei,
        types: 1,
        currentTab: that.data.currentTab,
      },
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded" //post
      },
      success: function (res) {
        console.log("************************123*************************");
        console.log(res);
        wx.setStorage({
          key: 'map_add_key',
          data: '',
        })
        wx.setStorage({
          key: 'title_key',
          data: '',
        })
        wx.setStorage({
          key: 'jingwei_key',
          data: '',
        })
        wx.reLaunch({
          url: '/pages/index/index?currentTab=' + that.data.currentTab
        })
      }
    })
       

 return true;
    
  },

// 点击下方地址选择回填到上方
  getadd:function(e){
    var map_add = e.currentTarget.dataset.address;
    var address = e.currentTarget.dataset.title;
    var jingwei = e.currentTarget.dataset.jingwei;
    this.setData({
      locationAddress: map_add,
      address2: address,
      jingwei: jingwei
    })
  },
  getadd2: function (e) {
    console.log("-------------------------------------")
    console.log(e)
    var map_add = e.currentTarget.dataset.map_add;
    var address = e.currentTarget.dataset.address;
    var jingwei = e.currentTarget.dataset.jingwei;
    this.setData({
      locationAddress: map_add,
      address2: address,
      jingwei: jingwei
    })
  },
  changeMarkerColor: function (data, i) {
    var that = this;
    var markers = [];
    for (var j = 0; j < data.length; j++) {
      if (j == i) {
        // 此处需要在相应路径放置图片文件 
        data[j].iconPath = "../../img/marker_yellow.png";
      } else {
        // 此处需要在相应路径放置图片文件 
        data[j].iconPath = "../../img/marker_red.png";
      }
      markers[j](data[j]);
    }
    that.setData({
      markers: markers
    }); 

  },
  skiped:function(){
    // wx.navigateTo({
    //   url: '/pages/index/index',
    // })
  },
  footerTap: app.footerTap
})